using System;
using com.youzu.warh.protocol;
using DestroyIt;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Gameplay.Liberty.Pool;
using AudioStudio;
using Yoozoo.Mars.Got;
using AnimationState = Yoozoo.Gameplay.Liberty.AI.AnimationState;

namespace Yoozoo.Gameplay.Liberty
{
    public class Grenade : BaseThrowable
    {
        public Collider Trigger;
        public LayerMask groundMask;
        
        // 爆炸特效
        private int _currentEffectResID;
        private Transform _currentEffect;
        
        protected override void OnInitComplete()
        {
            
        }

        protected override void OnDestroy()
        {
            hideEffect(null);

            base.OnDestroy();
        }

        protected override void Update()
        {
            base.Update();
            
            // 遍历触发元素
            for (int i = 0; i < _WeaponBulletDataConfig.elements.Count; ++i)
            {
                if (!_triggerElementIndices.Contains(i))
                {
                    switch ((WeaponBulletEffectiveType)_WeaponBulletDataConfig.effective_time[i * 2])
                    {
                        case WeaponBulletEffectiveType.Delay:
                            {
                                if(_LifeTimer >= _WeaponBulletDataConfig.effective_time[i * 2 + 1])
                                {
                                    _triggerElementIndices.Add(i);
                                    TriggerWeaponBulletElement(_WeaponBulletDataConfig.elements[i]);
                                }
                            }
                            break;
                    }
                }
            }
        }
        // 检测碰撞发生
        private void OnCollisionEnter(Collision collision)
        {
            // 检测碰撞对象是否是地面
            if (collision.gameObject.layer == groundMask)
            {
                if (Trigger!=null)
                {
                    Trigger.enabled = true;
                }
            }
        }
        /// <summary>
        /// 触发武器子弹元素
        /// </summary>
        /// <param name="bullet"></param>
        /// <param name="elementId"></param>
        void TriggerWeaponBulletElement(int elementId)
        {
            if (Trigger!=null)
            {
                Trigger.enabled = false;
            }
            PbWeaponElementDataConfig weaponElementDataConfig = LibertyConfigManager.GetInstance().GetWeaponElementDataConfig(elementId);
            if (weaponElementDataConfig != null)
            {
                switch ((WeaponElementType)weaponElementDataConfig.element_type)
                {
                    case WeaponElementType.AttenuationDamage:
                        {
                            // 衰减伤害
                            int count = 0;
                            Collider[] results = PhysicsUtils.OverlapSphereNonAlloc(out count, transform.position, weaponElementDataConfig.parameter_01, BattleAgent.HandGunOnHitLayerMaskNames);

                            for (int i = 0; i < count; ++i)
                            {
                                Collider collider = results[i];

                                if (BattleAgent.CheckIsEnemyByTag(SideType.Grenade, collider))
                                {
                                    AIEntity aiEntity = BattleAgent.TryGetAIEntityFromCollider(collider);
                                    if (aiEntity)
                                    {
                                        int damageHP = calculateAttenuationDamage(weaponElementDataConfig, collider);
                                        if (damageHP > 0)
                                        {
                                            aiEntity.battleAgent.OnHit(_aiEntity, damageHP, AnimationState.BulletElement, false, _WeaponDataConfig.weapon_id);
                                        }
                                    }
                                    else
                                    {
                                        //命中场景物体
                                        Destructible destructible = BattleAgent.TryGetDestructibleyFromCollider(collider);
                                        if (destructible!=null)
                                        {
                                            int damageHP = calculateAttenuationDamage(weaponElementDataConfig, collider);
                                            if (damageHP > 0)
                                            {
                                                var interact_type = weaponElementDataConfig.interact_type;
                                                if (interact_type != 0)
                                                {
                                                    var times = 1;
                                                    var interacterCfg = LibertyConfigManager.GetInstance().GetWeaponInteractDataConfig(interact_type,(int)destructible.DestructibleType);
                                                    if (interacterCfg!=null)
                                                    {
                                                        times = interacterCfg.dmg_coef / 10000;
                                                    }
                                                    destructible.ApplyDamage(damageHP * times);
                                                }
                                            }
                                        }
                                    }
                                }
                                
                            }

                        }
                        break;

                    case WeaponElementType.Force:
                        {
                            // 冲量
                            int count = 0;
                            Collider[] results = PhysicsUtils.OverlapSphereNonAlloc(out count, transform.position, weaponElementDataConfig.parameter_02, BattleAgent.HandGunOnHitLayerMaskNames);

                            for (int i = 0; i < count; ++i)
                            {
                                Collider collider = results[i];
                                
                                Rigidbody rigidbody = BattleAgent.TryGetRigidbodyFromCollider(collider);
                                if (rigidbody != null)
                                {
                                    var direction = (collider.transform.position - transform.position).normalized;
                                    var force = weaponElementDataConfig.parameter_03;
                                    rigidbody.AddForce(direction * force);
                                }
                                // // 命中敌人
                                // AIEntity aiEntity = TryGetAIEntityFromCollider(collider);
                                // if (aiEntity)
                                // {
                                //     if (aiEntity.viewer!=null)
                                //     {
                                //         var direction = (collider.transform.position - transform.position).normalized;
                                //         var force = weaponElementDataConfig.parameter_03;
                                //         if (aiEntity.viewer.locomotionAgent!=null)
                                //         {
                                //             aiEntity.viewer.locomotionAgent.AddForce(direction * force);
                                //         }
                                //     }
                                //
                                //     if (aiEntity.id == LibertyAIUtils.PLAYER_AI_ID)
                                //     {
                                //         var direction = (collider.transform.position - transform.position).normalized;
                                //         var force = weaponElementDataConfig.parameter_03;
                                //         LibertyAIUtils.PlayerController.viewAvatar.inputRootMotion.AddForce(direction * force /5);
                                //     }
                                // }
                            }
                        }
                        break;
                }

                
                if (weaponElementDataConfig.effect > 0)
                {
                    Transform effectTransform = LibertyPoolMgr.GetInstance().GetEffectObject(weaponElementDataConfig.effect);
                    effectTransform.position = transform.position;
                    effectTransform.SetActive(true);
                    _currentEffectResID = weaponElementDataConfig.effect;
                    _currentEffect = effectTransform;
                    Timers.inst.Add(1f, 1, hideEffect);
                    AudioManager.PlaySound("am_street_player_impact", effectTransform.gameObject);
                }
            }
        }
        
        void hideEffect(object o)
        {
            if (_currentEffect)
            {
                LibertyPoolMgr.GetInstance().RecycleEffect(_currentEffectResID, _currentEffect);
                _currentEffect = null;
            }
        }

        // 计算范围衰减伤害
        int calculateAttenuationDamage(PbWeaponElementDataConfig weaponElementDataConfig, Collider collider)
        {
            int damageHp = Mathf.FloorToInt((weaponElementDataConfig.parameter_01 - Vector3.Distance(collider.transform.position, transform.position))
                / weaponElementDataConfig.parameter_01 * _aiEntity.propertyDataConfig.basic_atk * weaponElementDataConfig.value / 10000f);
            return Mathf.Max(damageHp, 0);
        }
        
    }
}